package com.classload;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @Author: fxy
 * @Date: 2022/04/11/17:13
 * @Description:
 */
public class YunClassLoader extends ClassLoader{
    private String path;

    public YunClassLoader(String path) {
        this.path = path;
    }

    public YunClassLoader(String path, ClassLoader parentClassLoader) {
        super(parentClassLoader);
        this.path = path;
    }

    /**
     * 重写父类的findClass方法，在ClassLoader在执行 loadClass 方法时，
     * 如果父加载器不会加载类，就会调用当前重写的方法进行加载类
     */
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        BufferedInputStream bis = null;
        ByteArrayOutputStream baos = null;
        try {
            bis = new BufferedInputStream(new FileInputStream(path + name + ".class"));
            baos = new ByteArrayOutputStream();
            int len;
            byte[] data = new byte[1024];
            while ((len = bis.read(data)) != -1) {
                baos.write(data, 0, len);
            }
            //获取内存中的完整的字节数组的数据
            byte[] classByteArray = baos.toByteArray();
            //将字节数组转换为Class的实例
            return defineClass(null, classByteArray, 0, classByteArray.length);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != baos) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                if (null != bis) {
                    bis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}